package servlet;

import bean.CateInfo;
import bean.CateLevelOne;
import bean.CateLevelTwo;
import dao.CateDao;
import dao.impl.CateDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        CateDao cateDao = new CateDaoImpl();
        List<CateInfo> cateInfos = cateDao.cate();
        //将菜单列表整理成树状结构
        List<CateLevelOne> cateLevelOnes = new ArrayList<>();
        for (CateInfo cateInfo :
                cateInfos) {
            if (cateInfo.getParentId()==0) {
                CateLevelOne cateLevelOne = new CateLevelOne();
                cateLevelOne.setId(cateInfo.getId());
                cateLevelOne.setCateName(cateInfo.getCateName());
                cateLevelOnes.add(cateLevelOne);
            } else {
                for (CateLevelOne cateLevelOne :
                        cateLevelOnes) {
                    if (cateLevelOne.getId().equals(cateInfo.getParentId())) {
                        CateLevelTwo cateLevelTwo = new CateLevelTwo();
                        cateLevelTwo.setId(cateInfo.getId());
                        cateLevelTwo.setCateName(cateInfo.getCateName());
                        cateLevelTwo.setDes(cateInfo.getDes());
                        cateLevelTwo.setParentId(cateInfo.getParentId());
                        cateLevelOne.getChilds().add(cateLevelTwo);
                    }
                }
            }
        }
        //将整理后的菜单存入session
        session.setAttribute("cates", cateLevelOnes);
        resp.sendRedirect("goods/CateManage.jsp");
    }
}
